package com.platform.controller;

import com.gavel.utils.StringUtils;
import com.mrobuy.jdvc.entity.Menu;
import com.platform.model.AppInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@RestController
public class ApplicationController {

    private static Logger LOG = LoggerFactory.getLogger(ApplicationController.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/platform/api/init")
    public AppInfo appinit() {


        AppInfo.HomeInfoBean homeInfo = new AppInfo.HomeInfoBean();
        homeInfo.setTitle("首页");
        homeInfo.setHref("page/welcome-1.html?t=1");

        AppInfo.LogoInfoBean logoInfo = new AppInfo.LogoInfoBean();
        logoInfo.setTitle("帷易胜");
        logoInfo.setImage("images/logo.png");

        List<Menu> menuList =  jdbcTemplate.query("select * from MENU", new BeanPropertyRowMapper<>(Menu.class));

        ConcurrentHashMap<String, Menu> menuMap = new ConcurrentHashMap<>();
        for (Menu menu : menuList) {
            menuMap.put(menu.getId(), menu);
        }

        List<Menu> root = new ArrayList<>();
        for (Menu menu : menuList) {
            String pid = menu.getPid();
            if (StringUtils.isBlank(pid)) {
                root.add(menu);
                continue;
            }

            if ( menuMap.containsKey(pid) ) {
                menuMap.get(pid).getChild().add(menu);
            }
        }


        AppInfo appInfo = new AppInfo();
        appInfo.setHomeInfo(homeInfo);
        appInfo.setLogoInfo(logoInfo);
        appInfo.setMenuInfo(root);

        return appInfo;
    }

}
